package com.anjufang.controller;

import com.anjufang.dto.GroupDetailDto;
import com.anjufang.dto.GroupUserDto;
import com.anjufang.entity.GroupDetail;
import com.anjufang.entity.GroupInfo;
import com.anjufang.utils.ExcelDataFormatter;
import com.anjufang.utils.ExcelUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/group/excel")
public class GroupExcelController extends BaseController {

    @RequestMapping(value = "downExcel")
    @SuppressWarnings({ "unchecked", "static-access", "rawtypes" })
    public ResponseEntity<Resource> excelDown(@RequestParam Map<String, Object> params) throws Exception {

        List<GroupDetail> list = new GroupDetail().selectList("is_deleted = {0}", 0);
        List<GroupDetailDto> dtoList = new ArrayList<>();
        list.forEach(item -> {
            GroupDetailDto dto = new GroupDetailDto();
            BeanUtils.copyProperties(item, dto);
            dto.setHouseType("住宅");
            dtoList.add(dto);
        });
        ExcelDataFormatter edf = new ExcelDataFormatter();
        Workbook xlsx = new ExcelUtils(new GroupDetailDto()).getWorkBook(dtoList, edf);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        xlsx.write(bos);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
        headers.add(HttpHeaders.PRAGMA, "no-cache");
        headers.add(HttpHeaders.EXPIRES, "0");
        headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(bos.size()));
        // 设置下载文件名
        String filename = "抽签结果.xlsx";
        /*
         * IE的话，通过URLEncoder对filename进行UTF8编码。
         * 而其他的浏览器（firefox、chrome、safari、opera），则要通过字节转换成ISO8859-1了。
         */
        String userAgent = request.getHeader(HttpHeaders.USER_AGENT);// IE9之前包括IE9都包含MSIE;IE10之后都包含Trident;edge浏览器包含Edge
        if (userAgent.contains("MSIE") || userAgent.contains("Trident") || userAgent.contains("Edge")) {
            filename = URLEncoder.encode(filename, "UTF-8");
        } else {
            filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
        }
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filename + "\"");
        Resource resource = new InputStreamResource(new ByteArrayInputStream(bos.toByteArray()));
        return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);
    }

    /**
     * 分组及用户数据下载
     * @param params
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "downGroup")
    @SuppressWarnings({ "unchecked", "static-access", "rawtypes" })
    public ResponseEntity<Resource> groupDown(@RequestParam Map<String, Object> params) throws Exception {

        List<GroupInfo> groupInfoList = new GroupInfo().selectList("is_deleted = {0}", 0);
        List<GroupDetail> list = new GroupDetail().selectList("is_deleted = {0}", 0);
        List<GroupUserDto> dtoList = new ArrayList<>();
        list.forEach(item -> {
            GroupUserDto dto = new GroupUserDto();
            BeanUtils.copyProperties(item, dto);
            // 查找分组
            GroupInfo groupInfo = groupInfoList.stream().filter(x -> x.getId().equals(item.getGroupId())).findFirst().orElse(null);
            if(null != groupInfo) {
                dto.setGroupName(groupInfo.getGroupName());
                dto.setBeginTime(groupInfo.getBeginTime());
            }
            dtoList.add(dto);
        });
        ExcelDataFormatter edf = new ExcelDataFormatter();
        Workbook xlsx = new ExcelUtils(new GroupUserDto()).getWorkBook(dtoList, edf);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        xlsx.write(bos);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
        headers.add(HttpHeaders.PRAGMA, "no-cache");
        headers.add(HttpHeaders.EXPIRES, "0");
        headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(bos.size()));
        // 设置下载文件名
        String filename = "分组数据.xlsx";
        /*
         * IE的话，通过URLEncoder对filename进行UTF8编码。
         * 而其他的浏览器（firefox、chrome、safari、opera），则要通过字节转换成ISO8859-1了。
         */
        String userAgent = request.getHeader(HttpHeaders.USER_AGENT);// IE9之前包括IE9都包含MSIE;IE10之后都包含Trident;edge浏览器包含Edge
        if (userAgent.contains("MSIE") || userAgent.contains("Trident") || userAgent.contains("Edge")) {
            filename = URLEncoder.encode(filename, "UTF-8");
        } else {
            filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
        }
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filename + "\"");
        Resource resource = new InputStreamResource(new ByteArrayInputStream(bos.toByteArray()));
        return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);
    }

}
